<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="名称" class="filter-item" style="width: 200px;" @keyup.enter="handleFilter" />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate">新增</el-button>
    </div>

    <el-table :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="名称" min-width="100" />
      <el-table-column prop="description" label="描述" min-width="150" />
      <el-table-column prop="category" label="类别" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{row}">
          <el-tag :type="row.status === 0 ? 'primary' : 'success'">
            {{ row.status === 0 ? '待领取' : '已领取' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="地址" min-width="200">
        <template #default="{row}">
          {{ row.province + row.city + row.district + row.address }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="{row}">
          <el-button type="primary" size="small" @click="handleUpdate(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      :total="total"
      v-model:current-page="listQuery.pageNum"
      v-model:page-size="listQuery.pageSize"
      @current-change="getList"
      layout="total, prev, pager, next"
    />

    <el-dialog :title="dialogStatus === 'create' ? '新增公益柜' : '编辑公益柜'" v-model="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" label-position="left" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" type="textarea" />
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-input v-model="temp.category" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="地址">
          <el-cascader
            v-model="addressValue"
            :options="addressOptions"
            @change="handleAddressChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="temp.address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCharityBoxList, createCharityBox, updateCharityBox, deleteCharityBox } from '@/api/charity-box'
import { addressData } from '@/utils/address-data'

const list = ref([])
const total = ref(0)
const listLoading = ref(true)
const dialogFormVisible = ref(false)
const dialogStatus = ref('')
const addressValue = ref([])

const statusOptions = [
  { label: '待领取', value: 0 },
  { label: '已领取', value: 1 }
]

const addressOptions = addressData

const listQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: undefined
})

const temp = reactive({
  id: undefined,
  name: '',
  description: '',
  category: '',
  status: 0,
  province: '',
  city: '',
  district: '',
  address: ''
})

const getList = async () => {
  listLoading.value = true
  try {
    const { data } = await getCharityBoxList(listQuery)
    list.value = data.records
    total.value = data.total
  } catch (error) {
    console.error('获取公益柜列表失败:', error)
  }
  listLoading.value = false
}

const handleFilter = () => {
  listQuery.pageNum = 1
  getList()
}

const resetTemp = () => {
  Object.assign(temp, {
    id: undefined,
    name: '',
    description: '',
    category: '',
    status: 0,
    province: '',
    city: '',
    district: '',
    address: ''
  })
  addressValue.value = []
}

const handleCreate = () => {
  resetTemp()
  dialogStatus.value = 'create'
  dialogFormVisible.value = true
}

const handleUpdate = (row) => {
  Object.assign(temp, row)
  addressValue.value = [temp.province, temp.city, temp.district]
  dialogStatus.value = 'update'
  dialogFormVisible.value = true
}

const handleAddressChange = (value) => {
  if (value.length === 3) {
    temp.province = value[0]
    temp.city = value[1]
    temp.district = value[2]
  }
}

const createData = async () => {
  try {
    await createCharityBox(temp)
    dialogFormVisible.value = false
    ElMessage({
      message: '创建成功',
      type: 'success'
    })
    await getList()
  } catch (error) {
    console.error('创建公益柜失败:', error)
  }
}

const updateData = async () => {
  try {
    await updateCharityBox(temp)
    dialogFormVisible.value = false
    ElMessage({
      message: '更新成功',
      type: 'success'
    })
    await getList()
  } catch (error) {
    console.error('更新公益柜失败:', error)
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该公益柜?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCharityBox(row.id)
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      await getList()
    } catch (error) {
      console.error('删除公益柜失败:', error)
    }
  })
}

onMounted(() => {
  getList()
})
</script>